RichTextBox for UWP | ComponentOne
Tutorials / Printing C1RichTextBox Contents / Step 3 of 4: Adding Application Code
In This Topic
    Step 3 of 4: Adding Application Code
    In This Topic

    In the previous step, you added a resource file and started adding code to your application. In this step, you'll add the rest of your application code.

    1. First, you'll add the event handlers for the Printing_Loaded, Printing_Unloaded, and btnPrint_Click events within and event handler region:
      C#
      Copy Code
      #region event handlers
              void Printing_Unloaded(object sender, RoutedEventArgs e)
              {
                  UnregisterForPrinting();
              }
              void Printing_Loaded(object sender, RoutedEventArgs e)
              {
                  // init printing
                  RegisterForPrinting();
              }
              private async void btnPrint_Click(object sender, RoutedEventArgs e)
              {
                  await Windows.Graphics.Printing.PrintManager.ShowPrintUIAsync();
              }
              #endregion
      

    2. Create another region for the printing implementation:
      C#
      Copy Code
       #region implemention
       #endregion
      

    3. Within the implementation region, add the PrintTaskRequested event handler:
      C#
      Copy Code
       /// <summary>
              /// This is the event handler for PrintManager.PrintTaskRequested.
              /// </summary>
              /// <param name="sender">PrintManager</param>
              /// <param name="e">PrintTaskRequestedEventArgs </param>
              protected void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e)
              {
                  PrintTask printTask = null;
                  printTask = e.Request.CreatePrintTask("SamplePDF", sourceRequested =>
                  {
                      // Print Task event handler is invoked when the print job is completed.
                      printTask.Completed += async (s, args) =>
                      {
                          // Notify the user when the print operation fails.
                          if (args.Completion == PrintTaskCompletion.Failed)
                          {
                              await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                              {
                                  MessageDialog dialog = new MessageDialog("Failed to print.");
                                  dialog.ShowAsync();
                              });
                          }
                      };
      

    4. Directly below the PrintTaskRequested event handler, set some options like the paper size and orientation:
      C#
      Copy Code
      // set print options like paper size and orientation
                      Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                      {
                          var layout = rtb.ViewManager.PresenterInfo as C1PageLayout;
                          if (layout != null && layout.Width > layout.Height)
                          {
                              printTask.Options.Orientation = PrintOrientation.Landscape;
                          }
                      });
                      sourceRequested.SetSource(printDocumentSource);
                  });
              }
      

    5. The method you'll add next registers the app for printing with Windows and sets up the event handlers for the print process:
      C#
      Copy Code
       /// <summary>
              /// This method registers the app for printing with Windows and sets up the necessary event handlers for the print process.
              /// </summary>
              protected void RegisterForPrinting()
              {
                  // Create the PrintDocument.
                  printDocument = new PrintDocument();
                  // Save the DocumentSource.
                  printDocumentSource = printDocument.DocumentSource;
                  // Add an event handler which sets up print preview.
                  printDocument.Paginate += Paginate;
                  // Add an event handler which provides a specified preview page.
                  printDocument.GetPreviewPage += GetPrintPreviewPage;
                  // Add an event handler which provides all final print pages.
                  printDocument.AddPages += AddPrintPages;
                  // Create a PrintManager and add a handler for printing initialization.
                  PrintManager printMan = PrintManager.GetForCurrentView();
                  printMan.PrintTaskRequested += PrintTaskRequested;
              }
      

    6. Add the method that un-registers the app for printing:
      C#
      Copy Code
       /// <summary>
              /// This method unregisters the app for printing with Windows.
              /// </summary>
              protected void UnregisterForPrinting()
              {
                  if (printDocument == null)
                      return;
                  printDocument.Paginate -= Paginate;
                  printDocument.GetPreviewPage -= GetPrintPreviewPage;
                  printDocument.AddPages -= AddPrintPages;
                  // Remove the handler for printing initialization.
                  PrintManager printMan = PrintManager.GetForCurrentView();
                  printMan.PrintTaskRequested -= PrintTaskRequested;
              }
      

    7. The last code you'll add within the implementation region contains three event handlers:
      C#
      Copy Code
        /// <summary>
              /// This is the event handler for PrintDocument.Paginate.
              /// It fires when the PrintManager requests print preview
              /// </summary>
              /// <param name="sender">PrintDocument</param>
              /// <param name="e">Paginate Event Arguments</param>
              protected void Paginate(object sender, PaginateEventArgs e)
              {
                  pages.Clear();
                  viewManager = new C1RichTextViewManager
                  {
                      Document = rtb.Document,
                      PresenterInfo = rtb.ViewManager.PresenterInfo
                  };
                  PrintDocument printDoc = (PrintDocument)sender;
                  // Report the number of preview pages
                  printDoc.SetPreviewPageCount(rtb.ViewManager.Presenters.Count, PreviewPageCountType.Intermediate);
              }
              /// <summary>
              /// This is the event handler for PrintDocument.GetPrintPreviewPage. It provides a specific print preview page,
              /// in the form of an UIElement, to an instance of PrintDocument. PrintDocument subsequently converts the UIElement
              /// into a page that the Windows print system can deal with.
              /// </summary>
              /// <param name="sender">PrintDocument</param>
              /// <param name="e">Arguments containing the preview requested page</param>
              protected void GetPrintPreviewPage(object sender, GetPreviewPageEventArgs e)
              {
                  // Add the first page
                  if (e.PageNumber == 1)
                      AddOnePrintPreviewPage(0);
                  PrintDocument printDoc = (PrintDocument)sender;
                  printDoc.SetPreviewPage(e.PageNumber, pages[e.PageNumber - 1]);
                  // Add the other pages
                  if (e.PageNumber == 1)
                      for (int i = 1; i < viewManager.Presenters.Count; i++)
                          AddOnePrintPreviewPage(i);
              }
              /// <summary>
              /// This is the event handler for PrintDocument.AddPages. It provides all pages to be printed, in the form of
              /// UIElements, to an instance of PrintDocument. PrintDocument subsequently converts the UIElements
              /// into a pages that the Windows print system can deal with.
              /// </summary>
              /// <param name="sender">PrintDocument</param>
              /// <param name="e">Add page event arguments containing a print task options reference</param>
              protected void AddPrintPages(object sender, AddPagesEventArgs e)
              {
                  // Loop over all of the pages and add each one to be printed
                  foreach (FrameworkElement page in pages)
                  {
                      printDocument.AddPage(page);
                  }
                  PrintDocument printDoc = (PrintDocument)sender;
                  // Indicate that all of the print pages have been provided
                  printDoc.AddPagesComplete();
              }
              void AddOnePrintPreviewPage(int index)
              {
                  var page = (FrameworkElement)printTemplate.LoadContent();
                  page.DataContext = viewManager.Presenters[index];
                  if (!pages.Contains(page))
                      pages.Add(page);
              }
      

    In this step, you added application code. In the next step, you'll run the application.